package com.example.seakdreamandroid.sleep;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.FavoriteActivity;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.MusicStoryPlayerActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.bedtimeStory.BedtimeStory;
import com.example.seakdreamandroid.crosstalk.Crosstalk;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.sleep.entity.SleepInfo;
import com.example.seakdreamandroid.sleep.util.MediaUtil;
import com.example.seakdreamandroid.sleep.view.LongClickProgressView;
import com.example.seakdreamandroid.whiteNoise.WhiteNoiseActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class StartSleep extends AppCompatActivity {

    private TextView weakUpTime;
    private MediaRecorder recorder = null;
    private static String fileName = null;
    private String format,startTime;
    private SleepInfo sleepInfo = new SleepInfo();
    private User user;
    private ImageButton likeList,story;
    private int page = 0;

    // 申请录音权限
    private boolean permissionToRecordAccepted = false;
    private String [] permissions = {Manifest.permission.RECORD_AUDIO};
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_RECORD_AUDIO_PERMISSION:
                permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                break;
        }
        if (!permissionToRecordAccepted ) finish();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = (User) getApplication();
        sleepInfo.setSleepId(UUID.randomUUID().toString());
        sleepInfo.setUserId(user.getUserId());
        fileName = getExternalCacheDir().getAbsolutePath();
        fileName += "/audiorecordtest"+sleepInfo.getSleepId()+".3gp";
        ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
        setContentView(R.layout.activity_start_sleep);

        //开始录音
        Bundle bundle = getIntent().getExtras();
        page = bundle.getInt("page");
        if (page == 1) {
            startRecording();
        }
        getViews();
        setListener();
        startTime = bundle.getString("startTime");
        String hour = bundle.getString("hour");
        String minute = bundle.getString("minute");
        weakUpTime.setText(hour+":"+minute+"唤醒你");


        //到达设定时间
        oneTimeRing(Integer.valueOf(hour), Integer.valueOf(minute));

        //长按结束睡眠
        LongClickProgressView longClickProgressView = findViewById(R.id.btn_long_click_finish);
        longClickProgressView.setRingColor(Color.parseColor("#000000"));
        longClickProgressView.setCenterColor(Color.parseColor("#000000"));
        longClickProgressView.setOnLongClickStateListener(new LongClickProgressView.OnLongClickStateListener() {
            @Override
            public void onFinish() {
                //停止录音
                stopRecording();
                Date endTime = new Date();
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    /*
                     杨锐涵增加
                     */
                   /* if (user.isWhiteNoiseIsPlay()){
                        WhiteNoisePlayerService.getController().pausePlay(true);
                    }

                    if (user.isMSPIsPlay()){
                        user.setEnd(true);
                    }*/


                    long time = simpleDateFormat.parse(simpleDateFormat.format(endTime)).getTime()-simpleDateFormat.parse(startTime).getTime();
                    long min = time %  (1000 * 24 * 60 * 60)% (1000 * 60 * 60) / (1000 * 60);// 计算差多少分钟
                    //90分钟以内不会产生记录
//                    if (min < 90) {
//                        Intent intent = new Intent(StartSleep.this, MainActivity.class);
//                        intent.putExtra("id",1);
//                        startActivity(intent);
//                        Toast.makeText(StartSleep.this, "记录不足90分钟，无法生成报告", Toast.LENGTH_SHORT).show();
//                    } else {
                        sleepInfo.setAsleepTime(startTime);
                        sleepInfo.setAwakeTime(format);
                        //连接后端创建记录
                        postAsync();
//                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(StartSleep.this, "Cancel!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setListener() {
        likeList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(StartSleep.this, FavoriteActivity.class);
                startActivity(intent);
            }
        });
        story.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user.isMSPIsPlay()) {
                    Intent intent = new Intent();
                    intent.putExtra("audioUrl", user.getAudioUrl());
                    intent.putExtra("audioId", user.getAudioId());
                    intent.putExtra("audioName", user.getAudioName());
                    intent.putExtra("audioAuthor", user.getAudioAuthor());
                    intent.setClass(StartSleep.this, MusicStoryPlayerActivity.class);
                    startActivity(intent);
                } else if(user.isWhiteNoiseIsPlay()){

                    Intent intent = new Intent(StartSleep.this, WhiteNoisePlayerActivity.class);

                    startActivity(intent);
                } else{
                    Intent intent = new Intent(StartSleep.this, MusicStoryPlayerActivity.class);
                    intent.putExtra("audioUrl", "https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBcDBqdlhfVUliRW5nUnRuYlZ6WjRCNktHSEVTP2U9TnFzQTN3.mp3");
                    intent.putExtra("audioId", "61");
                    intent.putExtra("audioName", "海的女儿");
                    intent.putExtra("audioAuthor", "精选童话");
                    startActivity(intent);
                }

            }
        });
    }

    private void getViews() {
        weakUpTime = findViewById(R.id.weakUpTime);
        likeList = findViewById(R.id.like_list);
        story = findViewById(R.id.story);
    }

    private void oneTimeRing( int hourSet,int minuteSet) {
        //设定时间
        Date date = new Date();
        date.setHours(hourSet);
        date.setMinutes(minuteSet);
        int seconds = date.getSeconds();
        if (new Date().getHours() < hourSet || (new Date().getHours()==hourSet && new Date().getMinutes() < minuteSet)) {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            sleepInfo.setAwakeTime(format);
            sleepInfo.setAsleepTime(startTime);
            handle((date.getTime() - System.currentTimeMillis() - 1000*seconds) / 1000);
        }else if(date.getHours()>hourSet || (date.getHours()==hourSet && date.getMinutes()>minuteSet)){
            int date1 = date.getDate()+1;
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date1);
            sleepInfo.setAwakeTime(format);
            sleepInfo.setAsleepTime(startTime);
            date.setDate(date1);
            handle((date.getTime() - System.currentTimeMillis()-1000*seconds) / 1000);
        }
    }

    private void handle(long l) {
        new HandlerThread("TestThread") {
            protected void onLooperPrepared() {
                CountDownTimer countDownTimer = new CountDownTimer(1000L * (l), 1000L) {
                    @Override
                    public void onTick(long l) {
                        long minute = l / (1000 * 60); //单位分
                        long second = (l - minute * (1000 * 60)) / 1000;//单位秒
                        System.out.println(minute+":"+second);
                    }

                    @Override
                    public void onFinish() {
                        MediaUtil.playRing(StartSleep.this);
                        //关闭闹钟
                        AlertDialog.Builder builder = new AlertDialog.Builder(StartSleep.this);
                        builder.setTitle("关闭闹钟")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        MediaUtil.stopRing();
                                        stopRecording();
                                        postAsync();
                                    }
                                });
                        AlertDialog alertDialog = builder.create();
                        alertDialog.show();
                    }
                };
                countDownTimer.start();
            }
        }.start();
    }

    private void postAsync() {
        FormBody body= new FormBody.Builder()
                .add("sleepId",sleepInfo.getSleepId())
                .add("userId",sleepInfo.getUserId())
                .add("asleepTime",sleepInfo.getAsleepTime())
                .add("awakeTime",sleepInfo.getAwakeTime())
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"sleep/createSleepInfo")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okHttp","onfilure");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //修改用户界面，需要使用Handler或RunOnUiThread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent= new Intent(StartSleep.this,RecordPage.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("sleepInfo",sleepInfo);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            }
        });
    }


    private void stopRecording() {
        if(recorder != null) {
            recorder.stop();
        }
        recorder.release();
        recorder = null;
    }

    private void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e("StartSleep", "prepare() failed");
        }

        recorder.start();
    }


}